const log = require('../util/log')

module.exports = (req, res) => {
  require('../util/service').handlePost(req, res, (reqObj, resolve) => {
    const mongoMng = require('../mng/mongoMng')
    if (!mongoMng.db) {
      log('未连接mongo')
      resolve({
        result: -1,
        msg: '系统错误'
      })
      return;
    }
    if (!reqObj.alipay) {
      resolve({
        result: -1,
        msg: '缺少alipay'
      })
      return
    }
    if (!reqObj.code) {
      resolve({
        result: -1,
        msg: '缺少code'
      })
      return
    }
    var date = new Date()
    date.setTime(date.getTime() - 1800000)
    mongoMng.db.collection('code').find({
      phone: req.session.customer.phone,
      code: reqObj.code,
      time: {
        $gte: require('../../lib/formatDate')(date)
      }
    }).toArray((err, result) => {
      if (err) {
        log(err);
        resolve({
          result: -1,
          msg: '系统错误'
        })
        return;
      }
      if (result.length == 0) {
        resolve({
          result: -1,
          msg: '验证码错误'
        })
        return
      }
      mongoMng.db.collection('user').find({
        phone: req.session.customer.phone
      }).toArray((err, result) => {
        if (err) {
          log(err);
          resolve({
            result: -1,
            msg: '系统错误'
          })
          return;
        }
        if (result.length == 0) {
          mongoMng.db.collection('user').insert({
            phone: req.session.customer.phone,
            alipay: reqObj.alipay
          }, (err, result) => {
            if (err) {
              log(err);
              resolve({
                result: -1,
                msg: '系统错误'
              })
              return;
            }
            resolve({
              result: 1
            })
          });
        } else {
          mongoMng.db.collection('user').update({
            phone: req.session.customer.phone
          }, {
              $set: {
                alipay: reqObj.alipay
              }
            }, {
              multi: true
            }, (err, result) => {
              if (err) {
                log(err);
                resolve({
                  result: -1,
                  msg: '系统错误'
                })
                return;
              }
              resolve({
                result: 1
              })
            });
        }
      });
    })
  })
}
